package com.ruoyi.auth.service;

import com.ruoyi.auth.config.JedisPoolConfiguration;
import com.ruoyi.auth.config.WechatCondition;
import com.ruoyi.auth.config.WechatOpenProperties;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.open.api.impl.WxOpenInRedisConfigStorage;
import me.chanjar.weixin.open.api.impl.WxOpenMessageRouter;
import me.chanjar.weixin.open.api.impl.WxOpenServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;

/**
 * @author lobyliang
 */
@Service
@EnableConfigurationProperties({ WechatOpenProperties.class,JedisPoolConfiguration.class})
@Slf4j
@Conditional(WechatCondition.class)
public class WxOpenService extends WxOpenServiceImpl{
    @Autowired
    private WechatOpenProperties wechatOpenProperties;
    @Autowired
    private JedisPool jedisPool;
    //private volatile static JedisPool jedisPool;
    private WxOpenMessageRouter wxOpenMessageRouter;

    @PostConstruct
    public void init() {
        WxOpenInRedisConfigStorage inRedisConfigStorage = new WxOpenInRedisConfigStorage(jedisPool);
        inRedisConfigStorage.setComponentAppId(wechatOpenProperties.getComponentAppId());
        inRedisConfigStorage.setComponentAppSecret(wechatOpenProperties.getComponentSecret());
        inRedisConfigStorage.setComponentToken(wechatOpenProperties.getComponentToken());
        inRedisConfigStorage.setComponentAesKey(wechatOpenProperties.getComponentAesKey());
        setWxOpenConfigStorage(inRedisConfigStorage);
        wxOpenMessageRouter = new WxOpenMessageRouter(this);
        wxOpenMessageRouter.rule().handler((wxMpXmlMessage, map, wxMpService, wxSessionManager) -> {
            log.info("\n接收到 {} 公众号请求消息，内容：{}", wxMpService.getWxMpConfigStorage().getAppId(), wxMpXmlMessage);
            return null;
        }).next();
    }
    public WxOpenMessageRouter getWxOpenMessageRouter(){
        return wxOpenMessageRouter;
    }

//    private JedisPool getJedisPool() {
//        if (pool == null) {
//            synchronized (WxOpenServiceDemo.class) {
//                if (pool == null) {
//                    pool = new JedisPool(redisProperies, redisProperies.getHost(),
//                            redisProperies.getPort(), redisProperies.getConnectionTimeout(),
//                            redisProperies.getSoTimeout(), redisProperies.getPassword(),
//                            redisProperies.getDatabase(), redisProperies.getClientName(),
//                            redisProperies.isSsl(), redisProperies.getSslSocketFactory(),
//                            redisProperies.getSslParameters(), redisProperies.getHostnameVerifier());
//                }
//            }
//        }
//        return pool;
//    }
}
